import 'package:bilibili/http/core/hi_error.dart';
import 'package:bilibili/http/dao/home_dao.dart';
import 'package:bilibili/model/home_mo.dart';
import 'package:bilibili/util/toast.dart';
import 'package:bilibili/widget/hi_banner.dart';
import 'package:bilibili/widget/video_card.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

class HomeTabPage extends StatefulWidget {
  final String? name;
  final List<BannerMo>? bannerList;

  const HomeTabPage({super.key, this.name, this.bannerList});

  @override
  State<StatefulWidget> createState() {
    return _HomeTabPageState();
  }
}

class _HomeTabPageState extends State<HomeTabPage>
    with AutomaticKeepAliveClientMixin {
  List<VideoMo> vidoeList = [];
  int pageIndex = 0;

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: StaggeredGridView.countBuilder(
        crossAxisCount: 2,
        padding: EdgeInsets.only(left: 10, right: 10),
        itemCount: vidoeList.length,
        itemBuilder: (BuildContext context, int index) {
          if (index == 0 && widget.bannerList != null) {
            return Padding(
              padding: EdgeInsets.only(bottom: 0, top: 8),
              child: _banner(),
            );
          } else {
            return VideoCard(vidoeMo: vidoeList[index]);
          }
        },
        staggeredTileBuilder: (int index) {
          if (widget.bannerList != null && index == 0) {
            return StaggeredTile.fit(2);
          } else {
            return StaggeredTile.fit(1);
          }
        },
      ),
    );
  }

  _banner() {
    return Padding(
      padding: EdgeInsets.only(left: 0, right: 0, top: 0),
      child: HiBanner(widget.bannerList),
    );
  }

  void _loadData({loadMore = false}) async {
    if (!loadMore) {
      pageIndex = 1;
    }
    var currentIndex = pageIndex + (loadMore ? 1 : 0);

    try {
      HomeMo result = await HomeDao.get(widget.name!, pageIndex: currentIndex);
      setState(() {
        if (result.videoList == null) {
          return;
        }

        if (loadMore) {
          pageIndex++;
          vidoeList = [...vidoeList, ...result.videoList!];
        } else {
          vidoeList = result.videoList!;
        }
      });
    } on HiNetError catch (e) {
      print(e);
      showWarningToast(e.message);
    }
  }

  @override
  bool get wantKeepAlive => true;
}
